﻿using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using Portal.Environment;
using Portal.Interface;
using Portal.Language;

using System.Text;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        AjaxPro.Utility.RegisterTypeForAjax(typeof(Portal.Environment.Environments));
        AjaxPro.Utility.RegisterTypeForAjax(typeof(Portal.Environment.ChatServices));
        Session["AdminPortalTitle"] = Environments.GetAppSettings("AdminPortalTitle");
        Portal.Environment.Environments.SetEnvironment();
        if (Environments.GetAppSettings("SystemLocked").Equals("1"))
        {
            Response.Redirect("~/SystemLocked.aspx");
            return;
        }
        if (Environments.CurrentLoginUser == null)
        {
            Response.Redirect("~/login.aspx");
            return;
        }
        AjaxPro.Utility.RegisterTypeForAjax(typeof(WorkFlowLibrary.Reminder));
        LoadCurrentUserInfo();
        LoadWebPart();
        string Script="<script language=javascript>"+
                      "     function DetectFunctionForRole()"+
                      "     {"+
                      "         RoleIndex=document.getElementById(\"divSelectRoleFunction\").selectedIndex;"+
                      "         RoleId=document.getElementById(\"divSelectRoleFunction\").options[RoleIndex].value;" +
                      "         value=Portal.Environment.Environments.LoadFunctionAdmin(RoleId).value;" +
                      "         document.getElementById(\"divLeftMenuFunction\").innerHTML=value;"+
                      "     }"+
                     "</script>";
        string SelectRole =
              "<div class=\"box\">" +
              "<div class=\"box_title\">" + ResourceBLL.GetText("Home", "Role", "Vai trò sử dụng") + "</div>" +
              "<div class=\"box_body\">" +
              "<div class=cssSelectRole>"+ResourceBLL.GetText("Home","SelectRole","Chọn vai trò:")+"</div>"+
              "<select id=divSelectRoleFunction onchange=javascript:DetectFunctionForRole();>";
        DataTable dtRoles = Environments.ReadingRole(Environments.CurrentLoginUser.UserId);

        string FirstRoleId = "";
        if (System.Web.HttpContext.Current.Session["ActiveRoleId"] != null)
        {
            FirstRoleId = (string)System.Web.HttpContext.Current.Session["ActiveRoleId"];
        }
        for (int iIndex = 0; iIndex < dtRoles.Rows.Count; iIndex++)
        {
            string RoleId = (string)dtRoles.Rows[iIndex]["RoleId"];
            string RoleName = (string)dtRoles.Rows[iIndex]["RoleName"];
            if (iIndex == 0 && FirstRoleId.Trim().Length==0) FirstRoleId = RoleId;
            if(RoleId.Equals(FirstRoleId))
            {
                SelectRole += "<option selected value=\""+RoleId+"\">" + RoleName + "</option>";
            }
            else
            {
                SelectRole += "<option value=\""+RoleId+"\">" + RoleName + "</option>";
            }
        }
        SelectRole += "</select>"+
                           "</div>" +
                           "<div class=\"box_bottom\"></div>" +
                           "</div>";


        if(System.Web.HttpContext.Current.Session["ActiveMenuNewsByLongSite"]==null)System.Web.HttpContext.Current.Session["ActiveMenuNewsByLongSite"]="vie";
        string cBelongSite = (string)System.Web.HttpContext.Current.Session["ActiveMenuNewsByLongSite"];

   

        //string LawFunction = "";
        string FunctionText = "<div id=divLeftMenuFunction>" + Environments.LoadFunctionAdmin(FirstRoleId) + "</div>";
        placeHolderLeft.Controls.Clear();
        placeHolderLeft.Controls.Add(new System.Web.UI.LiteralControl(Script+SelectRole + FunctionText));

        Session["ActiveTheme"] = Environments.GetAppSettings("ActiveTheme");
        string InfoFooterText = "footer";
        try
        {
            InfoFooterText = (string)Environments.GetAppSettings("InfoFooterText");
        }
        catch { }

        string Info = "";
        if (Session["InfoTextFooter"] == null)
        {
            //lay du lieu tu bang html
            SqlConnection sqlConnection = new SqlConnection(Environments.ConnectionString);
            sqlConnection.Open();
            SqlCommand sqlCommand = sqlConnection.CreateCommand();
            sqlCommand.CommandText = "select * from TableHtml where Alias=@Alias and IsPublishing=1";
            sqlCommand.Parameters.Add("@Alias", SqlDbType.VarChar);
            sqlCommand.Parameters["@Alias"].Value = InfoFooterText;
            SqlDataAdapter sqlda = new SqlDataAdapter(sqlCommand);
            DataTable dtResult = new DataTable();
            sqlda.Fill(dtResult);
            if (dtResult.Rows.Count > 0)
            {
                Session["InfoTextFooter"]=(string)dtResult.Rows[0][Environments.ActiveLanguage+"Body"];
            }
        }
        else
        {
            Info = (string)Session["InfoTextFooter"];
        }
        placeHolderInfoFooter.Controls.Add(new System.Web.UI.LiteralControl(Info));

        string InfoTop = "";
        if (Session["InfoTop"] == null)
        {
            //lay du lieu tu bang html
            SqlConnection sqlConnection = new SqlConnection(Environments.ConnectionString);
            sqlConnection.Open();
            SqlCommand sqlCommand = sqlConnection.CreateCommand();
            sqlCommand.CommandText = "select * from TableHtml where Alias=@Alias and IsPublishing=1";
            sqlCommand.Parameters.Add("@Alias", SqlDbType.VarChar);
            sqlCommand.Parameters["@Alias"].Value = "InfoTop";
            SqlDataAdapter sqlda = new SqlDataAdapter(sqlCommand);
            DataTable dtResult = new DataTable();
            sqlda.Fill(dtResult);
            if (dtResult.Rows.Count > 0)
            {
                Session["InfoTop"] = (string)dtResult.Rows[0][Environments.ActiveLanguage + "Body"];
            }
            else
            {
                Session["InfoTop"] = "";
            }
        }
        else
        {
            InfoTop = (string)Session["InfoTop"];
        }

        InfoTop = (string)Session["InfoTop"];
        placeHolderLeftInfoTop.Controls.Add(new System.Web.UI.LiteralControl(InfoTop));


        string InfoBottom = "";
        if (Session["InfoBottom"] == null)
        {
            //lay du lieu tu bang html
            SqlConnection sqlConnection = new SqlConnection(Environments.ConnectionString);
            sqlConnection.Open();
            SqlCommand sqlCommand = sqlConnection.CreateCommand();
            sqlCommand.CommandText = "select * from TableHtml where Alias=@Alias and IsPublishing=1";
            sqlCommand.Parameters.Add("@Alias", SqlDbType.VarChar);
            sqlCommand.Parameters["@Alias"].Value = "InfoBottom";
            SqlDataAdapter sqlda = new SqlDataAdapter(sqlCommand);
            DataTable dtResult = new DataTable();
            sqlda.Fill(dtResult);
            if (dtResult.Rows.Count > 0)
            {
                Session["InfoBottom"] = (string)dtResult.Rows[0][Environments.ActiveLanguage + "Body"];
            }
            else
            {
                Session["InfoBottom"] = "";
            }
        }
        else
        {
            InfoBottom = (string)Session["InfoBottom"];
        }
        InfoBottom = (string)Session["InfoBottom"];
        placeHolderLeftInfoBottom.Controls.Add(new System.Web.UI.LiteralControl(InfoBottom));
        #region

        //        <ul>
            //    <li class="current_page_item"><a href="eDocman.aspx"><span>eDocman</span></a></li>
            //    <li><a href="auto.aspx"><span>Tự động hóa cửa hàng</span></a></li>
            //    <li><a href="http://mail.petrolimex.com.vn/owa"><span>Webmail</span></a></li>
        //</ul>
        #endregion
        string MenuText = "<ul>";
        string MenuXml = Environments.PathRoot + "\\Themes\\" + Environments.PortalAlias + "\\layout\\layout.xml";
        if (new System.IO.FileInfo(MenuXml).Exists)
        {
            DataSet dsMenu = new DataSet();
            dsMenu.ReadXml(MenuXml);
            if (dsMenu.Tables.Count > 0)
            {
                for (int iIndex = 0; iIndex < dsMenu.Tables[0].Rows.Count; iIndex++)
                {
                    string Caption = (string)dsMenu.Tables[0].Rows[iIndex]["Caption"];
                    string Url = (string)dsMenu.Tables[0].Rows[iIndex]["Url"];
                    if (Url.Trim().Length > 0)
                    {
                        MenuText += " <li><a href=\"\">" + Caption + "</a></li>";
                    }
                    else
                    {
                        MenuText += " <li>" + Caption + "</li>";
                    }
                }
            }
        }
        MenuText += "</ul>";
        placeHolderMenuBar.Controls.Clear();
        placeHolderMenuBar.Controls.Add(new System.Web.UI.LiteralControl(MenuText));
    }

    

    private void LoadCurrentUserInfo()
    {
        string Path = Environments.WorkingPath + "\\ResourceManager";
        string[] Dirs = System.IO.Directory.GetDirectories(Path);
        string SelectLanguageText =
            "<script language=javascript>\r\n" +
            "       function ChangeActiveLanguage()\r\n"+
            "       {\r\n"+
            "           LanguageIndex=document.getElementById(\"drpSelectLanguage\").selectedIndex;\r\n" +
            "           Language=document.getElementById(\"drpSelectLanguage\").options[LanguageIndex].value;\r\n" +
            "           retValue=Portal.Environment.Environments.SetActiveLanguage(Language).value;\r\n" +
            "           alert(retValue);\r\n"+
            "       }\r\n"+
            "</script>\r\n"+
            "<span class=divSelectLanguage class=cssSelectLanguageInHomePageTitle>"+ResourceBLL.GetText("Home", "SelectLanguage", "Ngôn ngữ:") + "<select class=\"cssSelectLanguageInHomePage\" id=drpSelectLanguage onchange=javascript:ChangeActiveLanguage();>\r\n";
        string[] Languages=Environments.GetLanguages();
        for (int iIndex = 0; iIndex < Languages.Length; iIndex++)
        {
            if (Environments.ActiveLanguage.Equals(Languages[iIndex]))
            {
                SelectLanguageText += "<option selected value=\"" + Languages[iIndex] + "\">" + Languages[iIndex] + "</option>";
            }
            else
            {
                SelectLanguageText += "<option value=\"" + Languages[iIndex] + "\">" + Languages[iIndex] + "</option>";
            }
        }
        SelectLanguageText += "</select></span>";

        string CurrentActiveSite = Portal.Environment.Environments.GetActiveSite();
        string SelectSite = " | Site: "+
                     "<select id=drpSelectSite onchange=javascript:ClientChangeActiveSite();>";
        string[] Sites = Environments.GetSites();
        for (int iIndex = 0; iIndex < Sites.Length; iIndex++)
        {
            if (CurrentActiveSite == null) CurrentActiveSite = "";
            if (CurrentActiveSite.Trim().Length == 0)
            {
                CurrentActiveSite= Sites[iIndex];
                new Portal.Environment.Environments().SetActiveSite(CurrentActiveSite);
            }
            if (Sites[iIndex].ToLower().Equals(CurrentActiveSite))
            {
                SelectSite += "<option selected value=\"" + Sites[iIndex] + "\">" + Sites[iIndex] + "</option>";
            }
            else
            {
                SelectSite += "<option value=\"" + Sites[iIndex] + "\">" + Sites[iIndex] + "</option>";
            }
        }
        SelectSite += "</select>";

        string Display = "guest";
        if (Environments.CurrentLoginUser != null)
        {
            Display = Environments.CurrentLoginUser.LoginName + " / " + Environments.CurrentLoginUser.FullName;
        }

        string DefaultPage = "default.aspx";
        if (Environments.CurrentLoginUser != null)
        {
            if (Environments.CurrentLoginUser.UserBackendAspx.Trim().Length > 0)
            {
                DefaultPage = Environments.CurrentLoginUser.UserBackendAspx + ".aspx";
            }
        }
        Display += " | <a class=cssGoHomeButton href=\""+DefaultPage+"\"><span>" + ResourceBLL.GetText("default", "Home", "Trang chủ") + "</span></a> | <a class=cssLoginButton href=\"Login.aspx\">" + ResourceBLL.GetText("Home", "LogOut", "Logout") + "</a>&nbsp;|&nbsp;<a class=cssChangePasswordButton href=\"javascript:window.open('Changepassword.aspx','_self');\">" + ResourceBLL.GetText("Home", "ChangePasswordText", "Mật khẩu") + "</a>";

        placeHolderLoginUser.Controls.Add(new System.Web.UI.LiteralControl("Login: "+Display));
        placeHolderLoginUser.Controls.Add(new System.Web.UI.LiteralControl(SelectSite));
        placeHolderLoginUser.Controls.Add(new System.Web.UI.LiteralControl(SelectLanguageText));
        
        //placeHolderLoginUser.Controls.Add(new System.Web.UI.LiteralControl("<a href=\"PlugServices/Chat/ChatRoom.aspx\">Chat</a>"));

        placeHolderFooter.Controls.Add(new System.Web.UI.LiteralControl(ResourceBLL.GetText("Home","FooterId","Hệ thống Portal phiên bản 1.0")));
        placeHolderFooter.Controls.Add(new System.Web.UI.LiteralControl("<br>Portal:" + Environments.PortalAlias));
        placeHolderFooter.Controls.Add(new System.Web.UI.LiteralControl("<br>Root:" + Environments.HttpAdminRoot));
        placeHolderFooter.Controls.Add(new System.Web.UI.LiteralControl("<br>Path:"+HttpContext.Current.Request.PhysicalPath));
        placeHolderFooter.Controls.Add(new System.Web.UI.LiteralControl("<br>Theme:" + (string)Environments.GetAppSettings("ActiveTheme")));
    }

  

    private void LoadWebPart()
    {
        try
        {
            string WebPartId = Request["WebPartId"];
            if (WebPartId == null)
            {
                if (Portal.Environment.Environments.GetAppSettings("DefaultWebPartId") != null)
                {
                    WebPartId = (string)Portal.Environment.Environments.GetAppSettings("DefaultWebPartId");
                }
            }

            if (WebPartId.Trim().Length == 0) return;
            Portal.Interface.WebPartInt
                LoadedWebPartInt = Portal.Environment.WebPartUtilities.FindWebPart(WebPartId);
            if (LoadedWebPartInt  == null)
            {
                placeHolderContent.Controls.Add(new System.Web.UI.LiteralControl("<div class=cssWebPartNotFound>" + ResourceBLL.GetText("Home","WebPartNotFound","Không tìm thấy webpart!") + "</div>"));
                return;
            }

            LoadParamCls loadParamCls = new LoadParamCls();
            string LoadedData = LoadedWebPartInt.RenderWebPart(loadParamCls);
            if (LoadedData.Trim().Length > 0)
            {
                string Content =
                              "<div class=\"box_700\">" +
                              "     <div class=\"box_title_700\">" + LoadedWebPartInt.Title + "</div>" +
                              "     <div class=\"box_body_700\">" + LoadedData + "</div>" +
                              "     <div class=\"box_bottom_700\"></div>" +
                              "</div>";

                placeHolderContent.Controls.Add(new System.Web.UI.LiteralControl(Content));
            }
            else
            {
                placeHolderContent.Controls.Clear();
                placeHolderContent.Controls.Add(new System.Web.UI.LiteralControl(
                    "<div class=\"box_700\">" +
                    "     <div class=\"box_title_700\">" + LoadedWebPartInt.Title + "</div>" +
                    "     <div class=\"box_body_700\">"));
                    LoadedWebPartInt.LoadSubControls(placeHolderContent, this.Page, loadParamCls);
                    placeHolderContent.Controls.Add(new System.Web.UI.LiteralControl("</div>" +
                            "     <div class=\"box_bottom_700\"></div>" +
                            "</div>"));
            }
        }
        catch (Exception ex)
        {
            placeHolderContent.Controls.Add(new System.Web.UI.LiteralControl( ex.Message.ToString()));
        }
    }
}
